package cool.zhoujie;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import cool.zhoujie.adapter.QueryAdapter;
import cool.zhoujie.db.DBUtil;
import cool.zhoujie.db.RecentPlay;
import cool.zhoujie.gson.Data_MoreSong;
import cool.zhoujie.gson.Data_QuerySong;
import cool.zhoujie.gson.Gson_MoreSong;
import cool.zhoujie.gson.Gson_QuerySong;
import cool.zhoujie.service.PlayService;
import cool.zhoujie.util.HttpResponse;
import cool.zhoujie.util.HttpUtil;

public class QueryActivity extends AppCompatActivity{

    private SearchView searchView;

    private ListView listView;

    private TextView loading;

    private List<Data_QuerySong> data_querySongList = new ArrayList<>();

    private QueryAdapter adapter;

    private ImageView btn_back;

    private PlayService playService;

    private PlayService.PlayBinder binder;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (PlayService.PlayBinder) service;
            playService = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query);
        bindViews();
        initViews();
        Intent intent = new Intent(this, PlayService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);
        transparent();
        setListener();
    }

    private void bindViews() {
        searchView = findViewById(R.id.search_view);
        listView = findViewById(R.id.search_result);
        loading = findViewById(R.id.search_loading);
        btn_back = findViewById(R.id.search_back);
    }

    private void initViews() {
        loading.setVisibility(View.GONE);
    }

    private void setListener() {
//        设置搜索文本监听
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//            点击搜索按钮时回调
            @Override
            public boolean onQueryTextSubmit(final String query) {
                searchView.clearFocus();
                new Thread(() -> doSearch(query)).start();
                return false;
            }

//            搜索内容改变时回调
            @Override
            public boolean onQueryTextChange(final String newText) {
                return false;
            }
        });

        btn_back.setOnClickListener(v -> {
            if (v.getId() == R.id.search_back) {
                Intent intent = new Intent(QueryActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });

        listView.setOnItemClickListener((parent, view, position, id) -> {
            Data_QuerySong data_querySong = data_querySongList.get(position);
            String search_id = data_querySong.id;
            new Thread(() -> doDetailSearch(search_id)).start();
        });
    }

    private void doDetailSearch(String search_id) {
        String address = Constant.More_song + search_id;

        HttpUtil.sendHttpRequest(address, new HttpResponse() {
            @Override
            public void showLoading() {

            }

            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                Gson_MoreSong gson_moreSong = gson.fromJson(response, Gson_MoreSong.class);
                Data_MoreSong data_moreSong = gson_moreSong.moreSong;

                playService.initMediaPlayer(data_moreSong.songLink);
                playService.play();

                RecentPlay recentPlay = new RecentPlay();
                recentPlay.songName = data_moreSong.songName;
                recentPlay.artistName = data_moreSong.artistName;
                recentPlay.songPic = data_moreSong.songPic;
                saveRecent(recentPlay);
            }
        });
    }

    private void transparent() {
        if (Build.VERSION.SDK_INT >= 23) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    private void saveRecent(RecentPlay recentPlay) {
        List<RecentPlay> recentPlayList = DBUtil.queryAll();
        for (int i = 0; i < recentPlayList.size(); i++) {
            RecentPlay recentPlay1 = recentPlayList.get(i);
            if (recentPlay1.songName.equals(recentPlay.songName) && recentPlay1.artistName.equals(recentPlay.artistName)) {
                DBUtil.delete(recentPlay1);
                Log.d(Constant.TAG_DB, "数据重复，删除成功");
            }
        }
        DBUtil.insert(recentPlay);
    }

    private void doSearch(String queryContent) {
        String query = "";
        try {
            query = URLEncoder.encode(queryContent, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String address = Constant.Query_song + query;
        HttpUtil.sendHttpRequest(address, new HttpResponse() {
            @Override
            public void showLoading() {
                runOnUiThread(() -> loading.setVisibility(View.VISIBLE));
            }

            @Override
            public void onResponse(String response) {
                runOnUiThread(() -> loading.setVisibility(View.GONE));
                Gson gson = new Gson();
                Gson_QuerySong gson_querySong = gson.fromJson(response, Gson_QuerySong.class);
                data_querySongList = gson_querySong.moreQuerySong.data_querySongList;
                adapter = new QueryAdapter(QueryActivity.this, R.layout.list_item_search, data_querySongList);
                runOnUiThread(() -> listView.setAdapter(adapter));
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
